from django.db import models
from django.utils import timezone
from datetime import datetime
# 引入Django自带的模型信号post_init和post_save
from django.db.models.signals import post_init, post_save # post_init表示在管理员单击'保存'按钮前触发信号；post_save表示在单击'保存'按钮后触发信号
from django.dispatch import receiver # 信号的接收采用装饰器@receiver来实现
from django.core.mail import send_mail



import os
from docxtpl import DocxTemplate
from docxtpl import InlineImage
from docx.shared import Mm, Inches, Pt

# Create your models here.
class Ad(models.Model):
    title = models.CharField(max_length=50,verbose_name='招聘岗位')
    description = models.TextField(verbose_name='岗位要求')
    publishDate = models.DateTimeField(max_length=20,default=timezone.now,verbose_name='发布时间')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = '招聘广告'
        verbose_name_plural = '招聘广告'
        ordering = ('-publishDate',) #     ording写错了;是ordering;这里还要注意加逗号,

class Resume(models.Model):
    name = models.CharField(max_length=20, verbose_name='姓名')
    personID = models.CharField(max_length=30, verbose_name='身份证号')
    sex = models.CharField(max_length=5, default='男', verbose_name='性别')
    email = models.EmailField(max_length=30, verbose_name='邮箱')# EmailField邮箱格式的验证
    birth = models.DateField(max_length=20,
                             default=datetime.strftime(datetime.now(),
                                                       "%Y-%m-%d"),
                             verbose_name='出生日期')
    edu = models.CharField(max_length=5, default='本科', verbose_name='学历')
    school = models.CharField(max_length=40, verbose_name='毕业院校')
    major = models.CharField(max_length=40, verbose_name='专业')
    position = models.CharField(max_length=40, verbose_name='申请职位')
    experience = models.TextField(blank=True,
                                  null=True,
                                  verbose_name='学习或工作经历')
    photo = models.ImageField(upload_to='contact/recruit/%Y_%m_%d', # %Y_%m_%d'按照日期来保存存储用户上传照片的文件夹
                              verbose_name='个人照片')
    grade_list = (
        (1, '未审'),
        (2, '通过'),
        (3, '未通过'),
    )
     # IntegerField由管理员通过后台管理系统进行操作
    status = models.IntegerField(choices=grade_list, # choices=grade_list,下拉菜单形式呈现
                                 default=1,
                                 verbose_name='面试成绩')
    publishDate = models.DateTimeField(max_length=20,
                                       default=timezone.now,
                                       verbose_name='提交时间')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '简历'
        verbose_name_plural = '简历'
        ordering = ('-status', '-publishDate') # 两个参数，采用的是字段联合的方式进行排序；先看审核与否，再看提交时间

# 信号接收采用装饰器@receiver来实现
@receiver(post_init, sender=Resume) # 第一个参数是信号类型，第二个参数是需要监控的模型类
def before_save_resume(sender, instance, **kwargs):
    instance.__original_status = instance.status # instance为传入的模型变量,保存前将值保存在instance.__original_status，通过比较前后变量的值查看变量


@receiver(post_save, sender=Resume)
def post_save_resume(sender, instance, **kwargs):
    # 用控制台输出状态查看触发器的效果,控制台分别输出1,2。当把简历的状态由未审改为通过
    # print(instance.__original_status) # 1
    # print(instance.status) # 2
    email = instance.email  # 应聘者邮箱
    EMAIL_FROM = '2993431608@qq.com'  # 企业QQ邮箱;暂时还不能发送邮箱，难道是因为我这个邮箱不是企业邮箱么
    if instance.__original_status == 1 and instance.status == 2:
        
        
        template_path = os.getcwd() + '/media/contact/recruit.docx'  #模板文件
        template = DocxTemplate(template_path) # 通过DocxTemplate()函数建立模板文件，该函数传入的参数是提前制作好的Word模板文件路径
        # 从instance实例中获取当前简历字段信息
        name = instance.name
        personID = instance.personID
        sex = instance.sex
        email = instance.email
        birth = instance.birth
        edu = instance.edu
        school = instance.school
        major = instance.major
        position = instance.position
        experience = instance.experience
        photo = instance.photo

        context = {
            'name': name,
            'personID': personID,
            'sex': sex,
            'email': email,
            'birth': birth,
            'edu': edu,
            'school': school,
            'major': major,
            'position': position,
            'experience': experience,
             # 图像字段通过特殊的InlineImage()函数进行替换
            'photo': InlineImage(template, photo, width=Mm(30), height=Mm(40)), 
        }# width和height参数分别用来设置最终在word中显示的宽度和高度
        
        template.render(context) # render()函数进行字段替换
        filename = '%s/media/contact/recruit/%s_%d.docx' % (
            os.getcwd(), instance.name, instance.id)
        template.save(filename)


        email_title = '通知：恒达科技招聘初试结果' # 邮件标题 邮件和word模板生成不能共存么，不然就报database is locked
        email_body = '恭喜您通过本企业初试' # 邮件主题内容
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) # 要不就是这个函数会结束主函数，需要放在最后
       
    elif instance.__original_status == 1 and instance.status == 3:
        email_title = '通知：恒达科技招聘初试结果'
        email_body = '很遗憾，您未能通过本企业初试，感谢您的关注'
        # send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])为啥要等于它
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])  # send_mail()函数把邮件发送出去
       
